'use client';

import React, { useEffect, useState } from 'react';
import { Form, Input, Select, Button, message, InputNumber } from 'antd';
import { useRouter } from 'next/navigation';
import { PageContainer } from '@ant-design/pro-components';
import { ArrowLeftOutlined } from '@ant-design/icons';

interface TeamFormData {
  teamName: string;
  status: 'active' | 'inactive';
  managerId: string;
  discount: number;
  remark: string;
  members: string[];
}

const TeamDetailPage = ({ params }: { params: { id: string } }) => {
  const router = useRouter();
  const [form] = Form.useForm<TeamFormData>();
  const [loading, setLoading] = useState(false);
  const [managers, setManagers] = useState<{ label: string; value: string }[]>([]);
  const [members, setMembers] = useState<{ label: string; value: string }[]>([]);
  const isEdit = params.id !== 'new';

  useEffect(() => {
    // 获取可选的管理员列表
    const fetchManagers = async () => {
      try {
        // TODO: 调用API获取管理员列表
        const mockManagers = [
          { label: '张三', value: '1' },
          { label: '李四', value: '2' },
        ];
        setManagers(mockManagers);
      } catch (error) {
        console.error('获取管理员列表失败:', error);
        message.error('获取管理员列表失败');
      }
    };

    // 获取可选的成员列表
    const fetchMembers = async () => {
      try {
        // TODO: 调用API获取成员列表
        const mockMembers = [
          { label: '王五 (18812341234)', value: '3' },
          { label: '赵六 (18812345678)', value: '4' },
        ];
        setMembers(mockMembers);
      } catch (error) {
        console.error('获取成员列表失败:', error);
        message.error('获取成员列表失败');
      }
    };

    // 如果是编辑模式，获取团队详情
    const fetchTeamDetail = async () => {
      try {
        setLoading(true);
        // TODO: 调用API获取团队详情
        const mockTeamDetail: TeamFormData = {
          teamName: '测试团队',
          status: 'active',
          managerId: '1',
          discount: 7.5,
          remark: '测试备注',
          members: ['3', '4'],
        };
        form.setFieldsValue(mockTeamDetail);
      } catch (error) {
        console.error('获取团队详情失败:', error);
        message.error('获取团队详情失败');
      } finally {
        setLoading(false);
      }
    };

    fetchManagers();
    fetchMembers();
    if (isEdit) {
      fetchTeamDetail();
    }
  }, [form, isEdit, params.id]);

  const handleSubmit = async (values: TeamFormData) => {
    try {
      setLoading(true);
      // TODO: 调用API保存团队信息
      console.log('保存团队信息:', values);
      
      message.success('保存成功');
      router.push('/teams');
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageContainer
      loading={loading}
      title={
        <div className="flex items-center gap-2">
          <Button 
            type="text" 
            icon={<ArrowLeftOutlined />} 
            onClick={() => router.back()}
          >
            返回
          </Button>
          <span>{isEdit ? '编辑团队' : '新增团队'}</span>
        </div>
      }
    >
      <div className="bg-white p-6 rounded-lg">
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          className="max-w-2xl"
        >
          <Form.Item
            label="团队名称"
            name="teamName"
            rules={[{ required: true, message: '请输入团队名称' }]}
          >
            <Input placeholder="请输入团队名称" />
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select
              options={[
                { label: '正常', value: 'active' },
                { label: '停用', value: 'inactive' },
              ]}
            />
          </Form.Item>

          <Form.Item
            label="团队管理员"
            name="managerId"
            rules={[{ required: true, message: '请选择团队管理员' }]}
          >
            <Select
              options={managers}
              placeholder="请选择团队管理员"
            />
          </Form.Item>

          <Form.Item
            label="团队折扣"
            name="discount"
            rules={[
              { required: true, message: '请输入团队折扣' },
              { type: 'number', min: 0, max: 10, message: '折扣必须在0-10之间' }
            ]}
            extra="可设置0-10，设置后团队内所有人使用团队余额/额度付款时可享受此折扣"
          >
            <InputNumber
              min={0}
              max={10}
              step={0.1}
              placeholder="请输入团队折扣"
              style={{ width: '100%' }}
              addonAfter="折"
            />
          </Form.Item>

          <Form.Item
            label="备注"
            name="remark"
          >
            <Input.TextArea
              rows={4}
              placeholder="请输入备注信息"
            />
          </Form.Item>

          <Form.Item
            label="团队成员"
            name="members"
            rules={[{ required: true, message: '请选择团队成员' }]}
          >
            <Select
              mode="multiple"
              options={members}
              placeholder="请选择团队成员"
            />
          </Form.Item>

          <Form.Item className="mt-6">
            <div className="flex gap-4">
              <Button onClick={() => router.back()}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                保存
              </Button>
            </div>
          </Form.Item>
        </Form>
      </div>
    </PageContainer>
  );
};

export default TeamDetailPage;